package com.sjp.myspring.beans.factory.support;

import com.sjp.myspring.beans.factory.config.JPBeanDefinition;
import com.sjp.myspring.utils.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class JPBeanDefinitionReader {

    private final static String SCAN_PACKAGE = "scanPacakge";

    private Properties config = new Properties();

    private List<String> registerBeanClasses = new ArrayList<>();

    public JPBeanDefinitionReader(String... locations) {

        try (InputStream inputStream =
                     this.getClass().getClassLoader()
                             .getResourceAsStream(locations[0].replace("classpath:", ""))
        ) {
            config.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        doScan(config.getProperty(SCAN_PACKAGE));

    }

    public Properties getConfig() {
        return config;
    }

    private void doScan(String scanPackage) {
        String name = "/" + scanPackage.replaceAll("\\.", "/");
        URL url = this.getClass().getResource(name);
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String className = scanPackage + "." + file.getName().replace(".class", "");
                registerBeanClasses.add(className);
            }
        }
    }

    /**
     * 把扫描到的类名转换为 JPBeanDefinition  以便后面IOC使用
     *
     * @return
     */
    public List<JPBeanDefinition> loadBeanDefinitions() {
        List<JPBeanDefinition> result = new ArrayList<>();
        for (String className : registerBeanClasses) {
            JPBeanDefinition jpBeanDefinition = doCreateBeanDefinition(className);
            if (jpBeanDefinition != null) {
                result.add(jpBeanDefinition);
            }
        }
        return result;
    }


    private JPBeanDefinition doCreateBeanDefinition(String className) {
        try {
            Class<?> beanClass = Class.forName(className);
            if (beanClass.isInterface()) {//bean 有可能是接口， 如果是接口，用它的实现类做beanClassName
                return null;
            }
            JPBeanDefinition beanDefinition = new JPBeanDefinition();
            beanDefinition.setBeanClassName(className);

            String factoryBeanName = StringUtils.lowercaseFirst(beanClass.getSimpleName());
            beanDefinition.setFactoryBeanName(factoryBeanName);
            return beanDefinition;

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
